package top.infopub.mgr.common.filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;


/**
 * Session超时filter
 * @author Awoke
 * @version 2018年10月15日
 * @see SessionPermFilter
 * @since
 */
public class SessionTimeOutFilter implements Filter {

    public SessionTimeOutFilter() {}

    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest)request;
        HttpServletResponse servletResponse = (HttpServletResponse)response;
        if ((servletRequest.getHeader("x-requested-with") != null && servletRequest.getHeader(
            "x-requested-with").equalsIgnoreCase("XMLHttpRequest"))
            || (servletRequest.getContentType() != null && servletRequest.getContentType().toLowerCase().indexOf(
                "multipart/form-data".toLowerCase()) > -1)
            || (request.getContentType() != null && request.getContentType().toLowerCase().indexOf(
                "application/x-www-form-urlencoded".toLowerCase()) > -1)) {
            Subject subject = SecurityUtils.getSubject();
            // session过期
            if (subject.getPrincipal() == null) {
                // 不拦截此方法 
                if (!servletRequest.getServletPath().equalsIgnoreCase("/wx/getCode")) {
                    // 设置状态码 前台页面捕获此状态码后，跳转到登录页
                    servletResponse.addHeader("sessionstatus", "timeout");
                    servletResponse.setStatus(401);
                }
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0)
        throws ServletException {

    }

}
